import router from "../../router";
const RouteOrient = (Dheader: any, Daside: any, path: string) => {
  const recursiveMenu = (
    path: string[],
    len = 0,
    menu = Daside.menu as any,
    result = [] as any
  ) => {
    if (path.length > 1) {
      path.shift();

      let index = menu.findIndex(
        (value: any) => value.to.split("/")[len + 1] == path[0]
      );
      len++;

      result.push(menu[index]);

      recursiveMenu(path, len, menu[index].submenu, result);
    }
    return result;
  };

  const routeOrient = (path: string) => {
    if (
      "submenu" in
      recursiveMenu(JSON.parse(JSON.stringify(path.split("/")))).pop()
    ) {
      router.replace({ path: "/home" });
      return;
    }
    Dheader.$patch((state: any) => {
      if (path == "/home") {
        state.header.row1.path.length = 0;
        return;
      }
      let result = recursiveMenu(JSON.parse(JSON.stringify(path.split("/"))));

      if (state.header.row1.path.length == 0) {
        state.header.row1.path = state.header.row1.path.concat(result);
        return;
      } else if (state.header.row1.path.at(-1).to == path) {
        return;
      } else {
        //判断重复部分
        let len =
          state.header.row1.path
            .at(-1)
            .to.split("/")
            .filter(
              (value: string, index: number) => index == path.indexOf(value)
            ).length - 1;
        state.header.row1.path.splice(len);
        state.header.row1.path = state.header.row1.path.concat(
          result.splice(len)
        );
      }
    });

    Dheader.$patch((state: any) => {
      if (path == "/home") {
        state.header.row2.activateTab = "/home";
        return;
      }
      let result = recursiveMenu(
        JSON.parse(JSON.stringify(path.split("/")))
      ).pop();

      if (
        state.header.row2.tabs.findIndex((value: any) => value.to == path) < 0
      ) {
        state.header.row2.tabs.push(result);
      }
      state.header.row2.activateTab = result.to;
    });
  };
  routeOrient(path);
};

export default RouteOrient;
